package com.ymttest.business.service;

import com.google.gson.Gson;
import com.ymatou.iapi.sellerproduct.parameter.BrandBean;
import com.ymatou.iapi.sellerproduct.parameter.CatalogLevelBean;
import com.ymatou.iapi.sellerproduct.service.ESsearchCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.*;
import com.ymttest.database.mongo.HistoryProductModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.bean.*;
import com.ymttest.database.mongo.jproduct.*;
import com.ymttest.database.sqlwapper.*;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.compare.AssertHelper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

public class NewJavaMongoCheckService {
	private static boolean changeObj2Bool(Object object) {
		try {
			if (object instanceof Boolean) {
				return (boolean) object;
			} else {
				int i = Integer.parseInt(object.toString());
				return i == 1 ? true : false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	
	private static Object changeAsDefaultIfNull(Object object, Object defaultVal){
		if (object==null || object.toString().equalsIgnoreCase("null")){
			return defaultVal;
		}else{
			return object;
		}
		
		
		
	}
	
	
	
	private static List<String> getMaxAndMinPrice(String productId) throws InterruptedException{
		List<String> priceList = new ArrayList<>();
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
		
		Map allMaxPrice = ymtCatalogsIWapper.selectAllMaxPrice(productId);
		Map allMinPrice = ymtCatalogsIWapper.selectAllMinPrice(productId);
		List<Map> minVipPriceMap = ymtCatalogsIWapper.selectVipPriceWithout0(productId);
		List<Map> minNewPriceMap = ymtCatalogsIWapper.selectNewPriceWithout0(productId);
		
		String allMaxStr = allMaxPrice.get("QuotePrice").toString() +","+ allMaxPrice.get("NewCustomerPrice").toString()+","+allMaxPrice.get("VipPrice").toString();

		
		
		String MinNewCustomerPrice = "0.00";
		if (minNewPriceMap.size()>0){
			MinNewCustomerPrice = minNewPriceMap.get(0).get("NewCustomerPrice").toString();
		}
		
		String MinVipPrice = "0.00";
		if (minVipPriceMap.size()>0){
			MinVipPrice = minVipPriceMap.get(0).get("VipPrice").toString();
		}
		
		
		
		String allMinStr = allMinPrice.get("QuotePrice").toString() +","+ MinNewCustomerPrice+","+MinVipPrice;
		
		priceList.add(allMaxStr);
		priceList.add(allMinStr);
		
		return priceList;
		
	}
	
	/***
	 * 检查指定productId
	 *  检查表Lives LiveProducts
	 * @param liveId
	 * @param productId
	 * @throws Exception
	 */
	public static void checkLiveMgoSyncBySQL_NewJavaMgo(int liveId,String productId,boolean isCheckBrand) throws Exception{
		
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			Logger.comment("检查Java Mongo直播相关 id:"+liveId);
			// check Mongo lives
			LivesWapper liveModelWapper = new LivesWapper();
			Logger.verifyEquals(1, liveModelWapper.getCountByActivityId(liveId), "Lives-直播数据应该只有1条");
			Map<String, Object> liveModelMap = liveModelWapper.getByActivityId(liveId);

			YmtLiveWapper ymtLiveWapper = new YmtLiveWapper();
			
			Map<String, Object> liveDataInSql = ymtLiveWapper.selectforMapByLiveId(liveId).get(0);

			Map<String, Object> liveDataInSqlTranlate = MapUtil.hashMap();
			liveDataInSqlTranlate.put("lid", liveDataInSql.get("iActivityId"));
			liveDataInSqlTranlate.put("name", liveDataInSql.get("sName"));
			liveDataInSqlTranlate.put("title", liveDataInSql.get("sTitle"));
			liveDataInSqlTranlate.put("content", liveDataInSql.get("sContent"));
			liveDataInSqlTranlate.put("sid", liveDataInSql.get("iSellerId"));
			liveDataInSqlTranlate.put("sname",
					LiveCallService.getLoginUserName(Integer.parseInt(liveDataInSql.get("iSellerId").toString())));
			liveDataInSqlTranlate.put("addr", liveDataInSql.get("sPosition"));
			liveDataInSqlTranlate.put("vcover", liveDataInSql.get("sVideoCover"));
			liveDataInSqlTranlate.put("vurl", liveDataInSql.get("sVideoUrl"));
			liveDataInSqlTranlate.put("action", liveDataInSql.get("iAction"));
			liveDataInSqlTranlate.put("confirm", liveDataInSql.get("bAppConfirmed"));
			liveDataInSqlTranlate.put("latlng", liveDataInSql.get("sLatlng"));
			//liveDataInSqlTranlate.put("pc", liveDataInSql.get("PutawayCount"));
			AssertService.assertResultEqual(liveDataInSqlTranlate, liveModelMap, "Mongo-Lives,compare with Sql");

			// 时间检查
			AssertService.assertTime((Date) liveDataInSql.get("dBeginTime"), (Date) liveModelMap.get("start"), 10,"Mongo-Lives start time");
			AssertService.assertTime((Date) liveDataInSql.get("dEndTime"), (Date) liveModelMap.get("end"), 10,"Mongo-Lives end time");
			AssertService.assertTime((Date) liveDataInSql.get("dAddTime"), (Date) liveModelMap.get("add"), 10,"Mongo-Lives add time");

			// 获取国家
			int countryId = Integer.parseInt(liveDataInSql.get("iCountryId").toString());
			AppCountry appcountry = new AppCountryWapper().selectByCountryId(countryId).get(0);
			Map<String, Object> otherMap = MapUtil.hashMap("country", appcountry.getScountrynamezh(), "flag",
					appcountry.getSflag());
			AssertService.assertResultEqual(otherMap, liveModelMap, "Mongo-Lives,compare with Sql");

			// ==========================================================
			// 直播下 商品检查
			
			List<String> productIds = new ArrayList<String>();
			if (productId!=null && !productId.equals("")){
				//检查指定productId
				productIds.add(productId);
			}else{
				productIds = LiveCallService.getProductsInLive(liveId);
			}

			// 检查品牌
			//workaround 某些场景 不修改直播品牌字段
			isCheckBrand = false;
			if (isCheckBrand){
				Logger.debug("Mongo-Lives 检查品牌");
				JSONArray tgtAry = new JSONArray(LiveCallService.getProdSBrandsInLive(liveId));
				if (tgtAry.length() == 0) {
					Logger.verifyIsNull(liveModelMap.get("brands"), "Mongo-Lives,compare with Sql");
				} else {
					
					String tmp = (liveModelMap.get("brands")!=null ?  
									liveModelMap.get("brands").toString(): "[]");
					
					JSONArray actAry = new JSONArray(tmp);
					AssertService.checkArray(tgtAry, actAry,"Mongo-Lives 品牌检查,期待品牌:"+tgtAry.toString()+",实际品牌:"+actAry.toString());
				}
			}else{
				Logger.debug("Mongo-Lives 不检查品牌");
			}

			// 检查liveProducts
			if (productIds.size()>0){
				
				LiveProductsWapper liveProductsWapper = new LiveProductsWapper();
				ProductTimeStampWapper productTimeStampWapper = new ProductTimeStampWapper();
				
				YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
				YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
				
				
				
				for (String prod : productIds) {
					Logger.comment("检查Java Mongo直播相关 id:"+liveId+", 商品id:"+prod);
					Map<String, Object> liveProductMap = liveProductsWapper.getByProductIdAndLiveId(prod, liveId);
					//liveProductMap.put("sort", new BigDecimal(liveProductMap.get("sort").toString()).toPlainString());
					
					
					Map<String, Object> productsInSql = ymtProductsIWapper.selectProductByProductIdforMap(prod).get(0);
					Map<String, Object> liveProductInSql = ymtProductsInLiveWapper.selectInLiveByProdIdAndLiveId(prod, liveId).get(0);
					
					Map<String, Object> liveProductInSqlTranlate = MapUtil.hashMap();
					liveProductInSqlTranlate.put("spid", prod);
					liveProductInSqlTranlate.put("lid", liveId);
					liveProductInSqlTranlate.put("sid", liveProductInSql.get("iUserId"));
					liveProductInSqlTranlate.put("comments", 0);
					//liveProductInSqlTranlate.put("sort", liveProductInSql.get("dReadyPutawayProductSort"));
					liveProductInSqlTranlate.put("istop", changeObj2Bool(liveProductInSql.get("iIsTop")));
					liveProductInSqlTranlate.put("status", liveProductInSql.get("iSellStatus"));
	
					//System.out.println(liveProductInSqlTranlate.get("sort"));
					//System.out.println(liveProductMap.get("sort"));
					
					
					BrandBean brandInfo = SellerProductCallService.getBrandInfoByProdId(prod);
							
					CatalogLevelBean catalogInfo = SellerProductCallService.getProductCategroyByThirdCategoryId(
							Integer.parseInt(productsInSql.get("iThirdCategoryId").toString()));
	
					
					liveProductInSqlTranlate.put("brand", brandInfo.getBrandName());
					liveProductInSqlTranlate.put("ebrand", brandInfo.getBrandEnName());
					liveProductInSqlTranlate.put("bid", brandInfo.getBrandId());
					liveProductInSqlTranlate.put("mcatid", catalogInfo.getMasterCategoryId());
					liveProductInSqlTranlate.put("mcatname", catalogInfo.getMasterCategoryName());
					liveProductInSqlTranlate.put("scatid", catalogInfo.getSecondCategoryId());
					liveProductInSqlTranlate.put("scatname", catalogInfo.getSecondCategoryName());
					liveProductInSqlTranlate.put("tcatid", catalogInfo.getThirdCategoryId());
					liveProductInSqlTranlate.put("tcatname", catalogInfo.getThirdCategoryName());
	
					AssertService.assertResultEqual(liveProductInSqlTranlate, liveProductMap,"Mongo-LiveProducts,compare with Sql");
					AssertService.assertTime((Date) liveProductInSql.get("dStartTime"), (Date) liveProductMap.get("start"),10,"Mongo-LiveProducts start time");
					AssertService.assertTime((Date) liveProductInSql.get("dEndTime"), (Date) liveProductMap.get("end"), 10,"Mongo-LiveProducts end time");
					AssertService.assertTime((Date) liveProductInSql.get("dAddTime"), (Date) liveProductMap.get("add"), 10,"Mongo-LiveProducts add time");
	
					
					//check productTimeStamp
					Logger.verifyEquals(1, productTimeStampWapper.getCountByProductId(prod), "Mongo-ProductTimeStamp - 记录应该只有一个");
					Map<String,Object> timeInMgo = productTimeStampWapper.getByProductId(prod);
					Date currentDate = YMTDateUtil.getDate();
					AssertService.assertTime(currentDate, (Date) timeInMgo.get("lut"), 300,"Mongo-ProductTimeStamp lut");
					
				}
			}
			
			
			
			if (productId!=null &&!productId.equals("")){
				EsProductCallService.checkEsProduct(productId);
			}

			
		}
		
		
		
		
	}
	
	/***
	 * 检查直播下所有商品
	 *  检查表Lives LiveProducts
	 * @param liveId
	 * @throws Exception
	 */
	public static void checkLiveMgoSyncBySQL_NewJavaMgo(int liveId) throws Exception {
		checkLiveMgoSyncBySQL_NewJavaMgo(liveId,"");

	}
	

	/***
	 * 检查直播和指定productid
	 * 
	 * 检查表Lives LiveProducts
	 * @param liveId
	 * @param productId 如果没有指定productid，将检查直播表下所有商品
	 * @throws Exception
	 */
	public static void checkLiveMgoSyncBySQL_NewJavaMgo(int liveId,String productId) throws Exception{
		checkLiveMgoSyncBySQL_NewJavaMgo(liveId,productId,false);
	}
	public static void checkLiveMgoSyncBySQL_NewJavaMgo(int liveId,boolean isCheckBrand) throws Exception {
		checkLiveMgoSyncBySQL_NewJavaMgo(liveId,"",false);

	}

	
	/***
	 *  检查表Products catalogs productDescExtra 
	 *   --productDescriptions
	 *  同时如商品有加入相关直播，则检查lives和liveproducts
	 * @param productId
	 * @param isCheckBrand 是否检查直播表中，品牌-由于某些场景下，不会修改直播表中品牌值
	 * @throws Exception
	 */
	public static void checkProductMgoSyncBySQL_NewJavaMgo(String productId,boolean isCheckBrand) throws Exception {
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			// Driver
			Logger.comment("检查Java mongo商品id: "+ productId);
			
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
			YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
			YmtProductPictureWapper ymtProductPictureWapper = new YmtProductPictureWapper();
			YmtProductVideoWapper ymtProductVideoWapper = new YmtProductVideoWapper();
			

			ProductsWapper productsWapper = new ProductsWapper();
			ProductDescExtraNewWapper productDescExtraWapper = new ProductDescExtraNewWapper();
			//ProductDescriptionsWapper productDescriptionsWapper = new ProductDescriptionsWapper();
			CatalogsWapper catalogsWapper = new CatalogsWapper();
			ProductTimeStampWapper productTimeStampWapper = new ProductTimeStampWapper();

			// to do
			// // ,ver ,verupdate
			// ============================================================================
			// 1- ProductInfo
			Map<String, Object> prodInfoMap = ymtProductsIWapper.selectProductByProductIdforMap(productId).get(0);
			Map<String, Object> prodTransInfoMap = MapUtil.hashMap();
			prodTransInfoMap.put("spid", productId);
			prodTransInfoMap.put("ipid", prodInfoMap.get("ipid"));
			prodTransInfoMap.put("title", prodInfoMap.get("sProduct"));
			prodTransInfoMap.put("intro", prodInfoMap.get("sMobileDescription"));
			// prodTransInfoMap.put("sPicUrl", prodInfoMap.get("pics"));
			prodTransInfoMap.put("intro", prodInfoMap.get("sMobileDescription"));
			prodTransInfoMap.put("sid", prodInfoMap.get("iUserId"));
			prodTransInfoMap.put("sname", prodInfoMap.get("SellerLoginId"));
			prodTransInfoMap.put("ctype", prodInfoMap.get("iCatalogType"));
			prodTransInfoMap.put("deliv", prodInfoMap.get("iCatalogStatus"));
			prodTransInfoMap.put("tariffy", prodInfoMap.get("iTariffType"));
			//prodTransInfoMap.put("shipping", prodInfoMap.get("fFlight"));
			prodTransInfoMap.put("country", prodInfoMap.get("SellerCountryId"));
			prodTransInfoMap.put("localr", prodInfoMap.get("iLocalReturn"));
			prodTransInfoMap.put("noreason", prodInfoMap.get("bNoReasonReturn"));
			prodTransInfoMap.put("action", prodInfoMap.get("iAction"));
			prodTransInfoMap.put("risk", prodInfoMap.get("bNoticeRisk"));
			prodTransInfoMap.put("pcode", prodInfoMap.get("sProductCode"));
			prodTransInfoMap.put("grade", prodInfoMap.get("sGrade"));
			
			prodTransInfoMap.put("isnew", changeObj2Bool(prodInfoMap.get("isNew")));
			prodTransInfoMap.put("istop", changeObj2Bool(prodInfoMap.get("isTop")));
			prodTransInfoMap.put("ispsp", changeObj2Bool(prodInfoMap.get("IsPspProduct")));
			prodTransInfoMap.put("bonded", changeAsDefaultIfNull(prodInfoMap.get("iBondedArea"),0));
			prodTransInfoMap.put("newdesc", true);
			
			
			
			//prodTransInfoMap.put("maxp", ymtCatalogsIWapper.selectMaxfQuotePrice(productId).get(0).get("MaxPrice"));
			//prodTransInfoMap.put("minp", ymtCatalogsIWapper.selectMinfQuotePrice(productId).get(0).get("MinPrice"));

			// 品牌品类
			
			BrandBean brandInfo = SellerProductCallService.getBrandInfoByProdId(productId);
			CatalogLevelBean catalogInfo = SellerProductCallService.getProductCategroyByThirdCategoryId(
					Integer.parseInt(prodInfoMap.get("iThirdCategoryId").toString()));

			//品牌中文名为空 就去品牌英文名
			prodTransInfoMap.put("brand", brandInfo.getBrandName());
			prodTransInfoMap.put("ebrand", brandInfo.getBrandEnName());
			prodTransInfoMap.put("bid", brandInfo.getBrandId());
			prodTransInfoMap.put("mcatid", catalogInfo.getMasterCategoryId());
			prodTransInfoMap.put("mcatname", catalogInfo.getMasterCategoryName());
			prodTransInfoMap.put("scatid", catalogInfo.getSecondCategoryId());
			prodTransInfoMap.put("scatname", catalogInfo.getSecondCategoryName());
			prodTransInfoMap.put("tcatid", catalogInfo.getThirdCategoryId());
			prodTransInfoMap.put("tcatname", catalogInfo.getThirdCategoryName());

			// mongo data
			Logger.verifyEquals(1, productsWapper.getCountByProductId(productId), "Products-商品数据应该只有1条");
			Map<String, Object> productInfoMgnMap = productsWapper.getByProductId(productId);
			AssertService.assertResultEqual(prodTransInfoMap, productInfoMgnMap, "Mongo-Products,compare with Sql");


			//商品视频
			List<YmtProductVideo> ymtProductExtList = ymtProductVideoWapper.selectByProductId(productId);
			if (ymtProductExtList.size()>0){
				YmtProductVideo ymtProductVideo = ymtProductExtList.stream().filter(x->x.getAction()==0).findFirst().orElse(null);
				JSONObject videoInMgo = new JSONObject(productInfoMgnMap.get("v").toString());
				Logger.verifyEquals(ymtProductVideo.getVideoPic(), videoInMgo.getString("p"), "商品视频 p");
				Logger.verifyEquals(ymtProductVideo.getVideoUrl(), videoInMgo.getString("u"), "商品视频 u");
				Logger.verifyEquals(ymtProductVideo.getVideoHeight(), videoInMgo.getInt("h"), "商品视频 h");
				Logger.verifyEquals(ymtProductVideo.getVideoSize(), videoInMgo.getInt("s"), "商品视频 s");
				Logger.verifyEquals(ymtProductVideo.getVideoWidth(), videoInMgo.getInt("w"), "商品视频 w");
			}
			
			
			// check date
			AssertService.assertTime((Date) prodInfoMap.get("validStart"), (Date) productInfoMgnMap.get("start"), 10,"Mongo-Products start time");
			AssertService.assertTime((Date) prodInfoMap.get("validEnd"), (Date) productInfoMgnMap.get("end"), 10,"Mongo-Products end time");
			AssertService.assertTime((Date) prodInfoMap.get("dAddTime"), (Date) productInfoMgnMap.get("addtime"), 10,"Mongo-Products add time");
			AssertService.assertTime((Date) prodInfoMap.get("dListingTime"), (Date) productInfoMgnMap.get("newstart"),10,"Mongo-Products new start");
			AssertService.assertTime((Date) prodInfoMap.get("dNewEndtime"), (Date) productInfoMgnMap.get("newend"), 10,"Mongo-Products new end");
			
			
			//check maxp and minp 
			List<String> priceList = getMaxAndMinPrice(productId);
			String[] maxPsinSql = priceList.get(0).split(",");
			String[] minPsinSql = priceList.get(1).split(",");
			
			String[] maxPsinMgo = productInfoMgnMap.get("maxp").toString().split(",");
			String[] minPsinMgo = productInfoMgnMap.get("minp").toString().split(",");
			
			Logger.verifyEquals(3, maxPsinMgo.length, "Mongo-Products 最高价应该有3个字段");
			Logger.verifyEquals(3, minPsinMgo.length, "Mongo-Products 最低价应该有3个字段");
			
			for(int i=0;i<3;i++){
				double maxPinSql = Double.parseDouble(maxPsinSql[i]);
				double maxPinMgo = Double.parseDouble(maxPsinMgo[i]);
				Logger.verifyEquals(maxPinSql, maxPinMgo, "Mongo-Products maxp 第"+(i+1));
				
				
				double minPinSql = Double.parseDouble(minPsinSql[i]);
				double minPinMgo = Double.parseDouble(minPsinMgo[i]);
				Logger.verifyEquals(minPinSql, minPinMgo, "Mongo-Products min 第"+(i+1));
				
			}
			//
			
			// pic
			JSONArray picsList = new JSONArray();
			ymtProductPictureWapper.selectByProductId(productId).forEach(ele -> 
			{ if (Integer.parseInt(ele.get("iAction").toString())>-1){
					picsList.put(ele.get("sOriUrl").toString());
				}
			});
			JSONArray picsMgo = new JSONArray(productInfoMgnMap.get("pics").toString());

			AssertService.checkArray(picsList, picsMgo);

			// ============================================================================
			// 2- ProductDescInfo
			List<Map> prodConfInfoMap = ymtProductsIWapper.selectDescPicConfigByProductId(productId);
			Map<String, Object> prodTransConfInfoMap = MapUtil.hashMap();

			prodTransConfInfoMap.put("desc", prodConfInfoMap.get(0).get("content"));
			prodTransConfInfoMap.put("spid", productId);

			// mongo data
			Logger.verifyEquals(1, productDescExtraWapper.getCountByProductId(productId),
					"ProductDescExtra-商品数据应该只有1条");
			Map<String, Object> productDescInfoMgnMap = productDescExtraWapper.getByProductId(productId);

			// check
			AssertService.assertResultEqual(prodTransConfInfoMap, productDescInfoMgnMap,
					"Mongo-ProductDescExtra,compare with Sql");

			// check pic
			JSONArray picsInSql = new JSONArray();
			prodConfInfoMap.forEach(ele -> picsInSql.put(ele.get("pic").toString()));
			JSONArray picsInMongo = new JSONArray(productDescInfoMgnMap.get("descpics").toString());
			AssertService.checkArray(picsInSql, picsInMongo, "Mongo-ProductDescExtra 图片检查");

			// ============================================================================
			// 3 CatalogsInfo
			List<Map> tmp = ymtCatalogsIWapper.selectCatalogsByProductIdforMap(productId);
			List<Map> catalogsInfoMap = new ArrayList<>();
			for(Map map:tmp){
				if (Integer.parseInt(map.get("iAction").toString())>-1){
					catalogsInfoMap.add(map);
				}
			}
			Logger.verifyEquals(catalogsInfoMap.size(), catalogsWapper.getCountByProductId(productId), "Catalogs-规格数量");
			for (Map catlogsInfo : catalogsInfoMap) {
				// data
				Map<String, Object> clogs = catlogsInfo;
				String catalogId = clogs.get("sCatalogId").toString();
				Logger.verifyEquals(1, catalogsWapper.getCountByCatalogId(catalogId), "Catalogs-商品规格数据应该只有1条");
				Map<String, Object> catalogInMgo = catalogsWapper.getByCatalogId(catalogId);

				Map<String, Object> catalogTransMap = MapUtil.hashMap();
				catalogTransMap.put("spid", productId);
				catalogTransMap.put("cid", catalogId);
				catalogTransMap.put("sku", clogs.get("sSKU"));
				catalogTransMap.put("presale", changeObj2Bool(clogs.get("IsPreSale")));
				catalogTransMap.put("earnest", changeAsDefaultIfNull(clogs.get("fEarnestPrice"),0));
				catalogTransMap.put("price", clogs.get("fQuotePrice"));
				catalogTransMap.put("newp", clogs.get("fNewCustomerPrice"));
				catalogTransMap.put("vip", clogs.get("fVipPrice"));
				catalogTransMap.put("stock", clogs.get("iNum"));
				
				//catalogTransMap.put("sid", prodInfoMap.get("iUserId"));
				

				AssertService.assertResultEqual(catalogTransMap, catalogInMgo, "Mongo-Catalogs,compare with Sql");

				// 规格属性值检查
				List<Map> catalogPropsMap = ymtCatalogsIWapper.selectCatalogPropsByCatalogId(catalogId);

				// 是否是多规格
				if (catalogPropsMap.size() == 0) {
					Logger.verifyIsNull(catalogInMgo.get("props"), "Mongo-Catalogs,单规格 pros为null");
				} else {
					JSONArray propsAry = new JSONArray(catalogInMgo.get("props").toString());
					Logger.verifyEquals(catalogPropsMap.size(), propsAry.length(), "Mongo-Catalogs,多规格属性值个数 应相同");

					for (Map catalogProp : catalogPropsMap) {
						Map<String, Object> propMap = catalogProp;
						Map<String, Object> propTransMap = MapUtil.hashMap();
						propTransMap.put("name", propMap.get("sProductProperty"));
						propTransMap.put("value", propMap.get("sCategoryAttribute"));
						propTransMap.put("pic", propMap.get("sPicUrl"));

						Map<String, Object> propInMgo = MapUtil.hashMap();
						for (int i = 0; i < propsAry.length(); i++) {
							// 获取当前匹配属性值
							if (propsAry.getJSONObject(i).getString("name")
									.equals(propTransMap.get("name").toString())) {
								propInMgo = MapUtil.jsonToMap(propsAry.getJSONObject(i));
								break;
							}
						}
						AssertService.assertResultEqual(propTransMap, propInMgo, "Mongo-Catalogs,pros属性值");
					}
				}

			}
			
			
			//4 直播相关
			//Logger.verifyEquals(LiveCallService.getLivesWithProduct(productId).size(),new LiveProductsWapper().getCountByProductId(productId), "Mongo-LiveProducts 应记录sql中有效直播");
			List<Integer> lives = LiveCallService.getLivesWithProduct(productId);
			lives.forEach(liveId->{
				try {
					checkLiveMgoSyncBySQL_NewJavaMgo(liveId, productId,false);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			
			
			//5 时间戳相关
			Logger.verifyEquals(1, productTimeStampWapper.getCountByProductId(productId), "Mongo-ProductTimeStamp - 记录应该只有一个");
			Map<String,Object> timeInMgo = productTimeStampWapper.getByProductId(productId);
			Date currentDate = YMTDateUtil.getDate();
			AssertService.assertTime(currentDate, (Date) timeInMgo.get("sut"), 600,"Mongo-ProductTimeStamp sut");
			AssertService.assertTime(currentDate, (Date) timeInMgo.get("cut"), 600,"Mongo-ProductTimeStamp cut");
			if (lives.size()>0){
				AssertService.assertTime(currentDate, (Date) timeInMgo.get("lut"), 600,"Mongo-ProductTimeStamp lut");
			}
			
		}
		
		
		
		//es check 
		//EsProductCallService.checkEsProduct(productId);
	}
	
	
	/***
	 *  检查表Products catalogs productDescriptions
	 *  同时如商品有加入相关直播，则检查lives和liveproducts
	 * @param productId
	 * @throws Exception
	 */
	public static void checkProductMgoSyncBySQL_NewJavaMgo(String productId) throws Exception {
		checkProductMgoSyncBySQL_NewJavaMgo(productId,true);

	}
	
	
	/***
	 * 商品删除action后 检查
	 * 检查products，action和时间等值
	 * 检查liveproducts和catalogs数据因删除
	 * @param productId
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static void checkProductAsDeleteMgoSyncBySQL_NewJavaMgo(String productId)throws Exception{
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			Logger.comment("检查Java mongo 删除商品id: "+ productId);
			
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
			YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
			
			ProductsWapper productsWapper = new ProductsWapper();
			CatalogsWapper catalogsWapper = new CatalogsWapper();
			LiveProductsWapper liveProductsWapper = new LiveProductsWapper();
			HistoryProductModelWapper historyProductModelWapper = new HistoryProductModelWapper();
			
			
			//sql data
			Map<String, Object> prodInfoMap = ymtProductsIWapper.selectProductByProductIdforMap(productId).get(0);
			
			Logger.verifyEquals(-2,Integer.parseInt(prodInfoMap.get("iAction").toString()),"删除商品，进入历史库后，iaction变为-2");
			
			
			// mongo data
			//products
			Logger.verifyEquals(0, productsWapper.getCountByProductId(productId), "Products-商品数据应该只有0条");

			//Catalogs
			Logger.verifyEquals(0, catalogsWapper.getCountByProductId(productId), "Catalogs-商品规格数据应该只有0条");
		
			//live product
			Logger.verifyEquals(0, liveProductsWapper.getCountByProductId(productId), "LiveProducts-直播商品数据应该只有0条");
			
			
			//检查历史库
			String prodInHis = historyProductModelWapper.getByProductIdAsStr(productId);
			
			
			HistoryProductBean actBean =  new Gson().fromJson(prodInHis.toString(),HistoryProductBean.class);
			
			BrandBean brandBean = SellerProductCallService.getBrandInfo(Integer.parseInt(prodInfoMap.get("iBrandId").toString()));
			CatalogLevelBean catalogLevelBean = SellerProductCallService.getProductCategroyByThirdCategoryId(Integer.parseInt(prodInfoMap.get("iThirdCategoryId").toString()));
			
			
			
			HistoryProductBean tgtBean = new HistoryProductBean();
			tgtBean.setAction(-1);
			tgtBean.setBondedArea(Integer.parseInt(changeAsDefaultIfNull(prodInfoMap.get("iBondedArea"),0).toString()));
			tgtBean.setBrandEnName(brandBean.getBrandEnName());
			tgtBean.setBrandName(brandBean.getBrandName());
			tgtBean.setBrandId(brandBean.getBrandId());
			tgtBean.setCatalogType(Integer.parseInt(prodInfoMap.get("iCatalogType").toString()));
			tgtBean.setMasterCategoryId(catalogLevelBean.getMasterCategoryId());
			tgtBean.setMasterCategoryName(catalogLevelBean.getMasterCategoryName());
			tgtBean.setCategoryId(catalogLevelBean.getSecondCategoryId());
			tgtBean.setCategoryName(catalogLevelBean.getSecondCategoryName());
			tgtBean.setThirdCategoryId(catalogLevelBean.getThirdCategoryId());
			tgtBean.setThirdCategoryName(catalogLevelBean.getThirdCategoryName());
			tgtBean.setCountryId(Integer.parseInt(prodInfoMap.get("SellerCountryId").toString()));
			tgtBean.setDeliveryMethod(Integer.parseInt(prodInfoMap.get("iCatalogStatus").toString()));
			//tgtBean.setFreight(Double.parseDouble(prodInfoMap.get("fFlight").toString()));
			//tgtBean.setIntroduction(prodInfoMap.get("sMobileDescription").toString());
			tgtBean.setIsNew(false);
			tgtBean.setIsNewDesc(true);
			tgtBean.setIsTop(changeObj2Bool(prodInfoMap.get("isTop")));
			tgtBean.setLocalReturn(Integer.parseInt(prodInfoMap.get("iLocalReturn").toString()));
			tgtBean.setMaxCatalogPrice(Double.parseDouble(ymtCatalogsIWapper.selectMaxfQuotePrice(productId).get(0).get("MaxPrice").toString()));
			tgtBean.setMinCatalogPrice(Double.parseDouble(ymtCatalogsIWapper.selectMinfQuotePrice(productId).get(0).get("MinPrice").toString()));
			tgtBean.setNoReasonReturn(changeObj2Bool(prodInfoMap.get("bNoReasonReturn")));
			tgtBean.setNoticeRisk(changeObj2Bool(prodInfoMap.get("bNoticeRisk")));
			tgtBean.setPicList(Arrays.asList(prodInfoMap.get("sPicUrl").toString()));
			tgtBean.setProductCode(prodInfoMap.get("sProductCode")==null?"":prodInfoMap.get("sProductCode").toString());
			tgtBean.setProductId(productId);
			tgtBean.setSellerId(Integer.parseInt(prodInfoMap.get("iUserId").toString()));
			tgtBean.setTariffType( Integer.parseInt(prodInfoMap.get("iTariffType").toString()));
			tgtBean.setTitle(prodInfoMap.get("sProduct").toString());
			tgtBean.setWeightUnit(Integer.parseInt(prodInfoMap.get("WeightUnit").toString()));
			
			
			//规格
			List<HisCatalogBean> catalogList = new ArrayList<>();
			
			List<Map> catalogsInSql = ymtCatalogsIWapper.selectCatalogsByProductIdforMap(productId);
			catalogsInSql.forEach(ele->{
				HisCatalogBean hisCatalogBean = new HisCatalogBean();
				hisCatalogBean.setCatalogId(ele.get("sCatalogId").toString());
				hisCatalogBean.setSKU(ele.get("sSKU")==null?"":ele.get("sSKU").toString());
				hisCatalogBean.setWeight(Double.parseDouble(ele.get("Weight").toString()));
				
				//价格list
				List<HisPriceBean> priceList = new ArrayList<>();
				
				if (Double.parseDouble(ele.get("fQuotePrice").toString())>0){
					HisPriceBean hisPriceBean = new HisPriceBean();
					hisPriceBean.setPrice(Double.parseDouble(ele.get("fQuotePrice").toString()));
					hisPriceBean.setPriceType(0);
					hisPriceBean.setProductInActivityId(0);
					hisPriceBean.setReason("原价");
					priceList.add(hisPriceBean);
				}
				
				if (Double.parseDouble(ele.get("fNewCustomerPrice").toString())>0){
					HisPriceBean hisPriceBean = new HisPriceBean();
					hisPriceBean.setPrice(Double.parseDouble(ele.get("fNewCustomerPrice").toString()));
					hisPriceBean.setPriceType(1);
					hisPriceBean.setProductInActivityId(0);
					hisPriceBean.setReason("新客价");
					priceList.add(hisPriceBean);
				}
				
				if (Double.parseDouble(ele.get("fVipPrice").toString())>0){
					HisPriceBean hisPriceBean = new HisPriceBean();
					hisPriceBean.setPrice(Double.parseDouble(ele.get("fVipPrice").toString()));
					hisPriceBean.setPriceType(2);
					hisPriceBean.setProductInActivityId(0);
					hisPriceBean.setReason("VIP价");
					priceList.add(hisPriceBean);
				}
				
				hisCatalogBean.setPriceList(priceList);
				
				//库存
				HisStockBean hisStockBean = new HisStockBean();
				hisStockBean.setProductInActivityId(0);
				hisStockBean.setStock(Integer.parseInt(ele.get("iNum").toString()));
				hisStockBean.setStockType(0);
				hisCatalogBean.setStockList(Arrays.asList(hisStockBean));
				
				
				//属性
				try {
					List<Map>  propertyMap = ymtCatalogsIWapper.selectCatalogAttributeByCatalogId(ele.get("sCatalogId").toString());
					if (propertyMap.size()>0){
						List<HisPropertyBean> propertyList = new ArrayList<>();
						propertyMap.forEach(x->{
							HisPropertyBean hisPropertyBean = new HisPropertyBean();
							hisPropertyBean.setName(x.get("sProductProperty").toString());
							hisPropertyBean.setValue(x.get("sCategoryAttribute").toString());
							propertyList.add(hisPropertyBean);
						});
						hisCatalogBean.setPropertyList(propertyList);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				catalogList.add(hisCatalogBean);
				
			});
			tgtBean.setCatalogList(catalogList);
			
			//运费模板
			List<Map> tmpsInSql = ymtProductsIWapper.getProductDeliveryTemplateByProdId(productId);
			List<HisTemplateBean> templates = new ArrayList<>();
		
			tmpsInSql.forEach(y->{
				HisTemplateBean hisTemplateBean = new HisTemplateBean();
				hisTemplateBean.setTemplateId(Integer.parseInt(y.get("TemplateId").toString()));
				hisTemplateBean.setCatalogStatus(Integer.parseInt(y.get("CatalogStatus").toString()));
				templates.add(hisTemplateBean);
			});
			tgtBean.setTemplates(templates);
		

			AssertHelper.assertResultEqual(tgtBean, actBean, "历史库检查");
		}
		
		//es检查
		if (YmtMongoDriverFactroy.IsEsCheck){
			if (productId!=null &&!productId.equals("")){
				Logger.verifyIsNull(new ESsearchCall().callandGetBean(productId),"删除商品不在es中");
			}
		}
	}
	
	
	

	
	
	
	public static void checkActivityProductMgoSyncBySQL_NewJavaMgo(int prodInActivityId) throws Exception{
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			Logger.comment("检查Java mongo 活动商品 productInActivity id: "+ prodInActivityId);
			
			Map<String, Object> tgtMap = MapUtil.hashMap();
			
			YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();
			YmtProductsInActivity ypia = ymtProductsInActivityWapper.selectByProductInActivityId(prodInActivityId);
			
			
			
			//活动id
			int activityId = ypia.getIactivityid();
			String sProductId =  ypia.getSproductid();
			
			//tgtMap.put("spid", ypia.getSproductid());
			tgtMap.put("aid", ypia.getIactivityid());
			tgtMap.put("inaid", ypia.getIproductinactivityid());
			tgtMap.put("market", ypia.getSmarketprice());
			
			YmtActivityWapper ymtActivityWapper = new YmtActivityWapper();
			YmtActivity ya = ymtActivityWapper.getRecordByActivityId(activityId);
			tgtMap.put("aname", ya.getSalesidename());
			
			//LimitNumType 为0 iLimitNum 就是活动限购数量
			//LimitNumType 为1  iLimitNum 就是活动商品限购数量
			if(ya.getLimitnumtype()==0){
				tgtMap.put("alimit", ya.getIlimitnum());
				tgtMap.put("plimit", 0);
			}else{
				//ya.getLimitnumtype()==1
				tgtMap.put("alimit", 0);
				tgtMap.put("plimit", ya.getIlimitnum());
			}
					
			int activityTmpId = ya.getIactivitytemplateid();
			YmtActivityTemplateWapper ymtActivityTemplateWapper = new YmtActivityTemplateWapper();
			YmtActivityTemplate yt = ymtActivityTemplateWapper.selectActivityTemplateById(activityTmpId);
			
			tgtMap.put("part", changeObj2Bool(yt.getIsPartCatalog()));
			tgtMap.put("isolation", changeObj2Bool(yt.getIsTradeIsolation()));
			
			
			
			//mongo data
			Map<String, Object> prodInActivityInMgo = new ActivityProductsWapper().getByProdInActivityId(prodInActivityId);
			
			//chekc 
			AssertService.assertResultEqual(tgtMap, prodInActivityInMgo,"Mongo-ActivityProducts 活动商品表检查");
			
			
			//catalogs
			YmtProductActivityStockWapper ymtProductActivityStockWapper = new YmtProductActivityStockWapper();
			List<Map> ypaswList = ymtProductActivityStockWapper.selectAllBy(MapUtil.hashMap("iProductInActivityId", prodInActivityId));
			YmtProductActivityStock ymtProductActivityStock = ymtProductActivityStockWapper.selectByProductInActivityId(prodInActivityId);
			
			JSONArray catalogsAry = new JSONArray(prodInActivityInMgo.get("catalogs").toString());
			Logger.verifyEquals(ypaswList.size(), catalogsAry.length(), "Mongo-ActivityProducts 规格数量应与sql相同");
			
			for (Map catalogProp : ypaswList) {
				String catalogId = catalogProp.get("sCatalogID").toString();
				Map<String, Object> catalogtgtMap = MapUtil.hashMap();
				catalogtgtMap.put("stock", catalogProp.get("iStockNum"));
				catalogtgtMap.put("price", catalogProp.get("fActivityPrice"));
				catalogtgtMap.put("cid", catalogProp.get("sCatalogID"));
	
				Map<String, Object> propInMgo = MapUtil.hashMap();
				for (int i = 0; i < catalogsAry.length(); i++) {
					// 获取当前匹配属性值
					if (catalogsAry.getJSONObject(i).getString("cid")
							.equals(catalogtgtMap.get("cid").toString())) {
						propInMgo = MapUtil.jsonToMap(catalogsAry.getJSONObject(i));
						break;
					}
				}
				catalogtgtMap.remove("cid");
				AssertService.assertResultEqual(catalogtgtMap, propInMgo, "Mongo-ActivityProducts,catalogs属性值");
			}
			
			//start time, end time
			AssertService.assertTime(ymtProductActivityStock.getDbegintime(), (Date) prodInActivityInMgo.get("start"), 10,"Mongo-ActivityProducts start time");
			AssertService.assertTime(ymtProductActivityStock.getDendtime(), (Date) prodInActivityInMgo.get("end"), 10,"Mongo-ActivityProducts end time");
			
			//===================================================================
			//共享库存检查
			YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
			CatalogsWapper catalogsWapper= new CatalogsWapper();
			List<Map> catalogsInSql = ymtCatalogsIWapper.selectCatalogsByProductIdforMap(sProductId);
			
			for(Map catalogInSql:catalogsInSql){
				String catalogId = catalogInSql.get("sCatalogId").toString();
				if (Integer.parseInt(catalogInSql.get("iAction").toString())>-1){
					Logger.verifyEquals(1, catalogsWapper.getCountByCatalogId(catalogId), "Mongo-Catalogs 规格应该存在，catalogId:"+catalogId);
					AssertService.assertResultEqual(MapUtil.hashMap("stock", catalogInSql.get("iNum")),catalogsWapper.getByCatalogId(catalogId),"Mongo-Catalogs 共享库存检查 catalogId: "+ catalogId );
					
				}else{
					Logger.verifyEquals(0, catalogsWapper.getCountByCatalogId(catalogId), "Mongo-Catalogs 规格应该action为-1应该删除，catalogId:"+catalogId);
				}
				
			}
			
			
			//检查时间戳
			ProductTimeStampWapper productTimeStampWapper = new ProductTimeStampWapper();
			Logger.verifyEquals(1, productTimeStampWapper.getCountByProductId(sProductId), "Mongo-ProductTimeStamp - 记录应该只有一个");
			Map<String,Object> timeInMgo = productTimeStampWapper.getByProductId(sProductId);
			Date currentDate = YMTDateUtil.getDate();
			AssertService.assertTime(currentDate, (Date) timeInMgo.get("aut"), 300,"Mongo-ProductTimeStamp aut");
			
			
			
			
		}
		
		
		
		//es check 
		YmtProductsInActivity ypia = new YmtProductsInActivityWapper().selectByProductInActivityId(prodInActivityId);
		String productId =  ypia.getSproductid();
		EsProductCallService.checkEsProduct(productId);
		
		
	}
	
	
	public static void checkProductStockMgoSyncBySQL_NewJavaMgo(String productId) throws Exception{
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
			YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
			CatalogsWapper catalogsWapper= new CatalogsWapper();
			List<Map> catalogsInSql = ymtCatalogsIWapper.selectCatalogsByProductIdforMap(productId);
			
			for(Map catalogInSql:catalogsInSql){
				String catalogId = catalogInSql.get("sCatalogId").toString();
				if (Integer.parseInt(catalogInSql.get("iAction").toString())>-1){
					Logger.verifyEquals(1, catalogsWapper.getCountByCatalogId(catalogId), "Mongo-Catalogs 规格应该存在，catalogId:"+catalogId);
					AssertService.assertResultEqual(MapUtil.hashMap("stock", catalogInSql.get("iNum")),catalogsWapper.getByCatalogId(catalogId),"Mongo-Catalogs 共享库存检查 catalogId: "+ catalogId );
					
				}else{
					Logger.verifyEquals(0, catalogsWapper.getCountByCatalogId(catalogId), "Mongo-Catalogs 规格应该action为-1应该删除，catalogId:"+catalogId);
				}
				
			}
		}
		
		//es check 
		EsProductCallService.checkEsProduct(productId);
		
		
	}
	
	
	
	public static void main(String[] args) throws Exception {
		NewJavaMongoCheckService.checkProductAsDeleteMgoSyncBySQL_NewJavaMgo("4925d5b8-65e6-41d3-a388-92b2843a2fd1");
	}
}
